import java.util.*;

/**
 * @author LKQ
 * @date 2022/4/14 9:03
 * @description
 */
public class Solution2 {
    public static void main(String[] args) {

    }
    public String minRemoveToMakeValid(String s) {
        Deque<Integer> index = new LinkedList<>();
        boolean[] noAdd = new boolean[s.length()];
        for(int i = 0; i < s.length(); i++) {
            char ch  = s.charAt(i);
            if (ch == ')') {
                if (index.isEmpty()) {
                    noAdd[i] = true;
                }else {
                    index.pop();
                }
            }else if (ch == '(') {
                index.push(i);
            }
        }
        // 剩余的左括号不能加入
        for (int a: index) {
            noAdd[a] = true;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (!noAdd[i]) {
                sb.append(s.charAt(i));
            }
        }
        return sb.toString();
    }
}
